<!--
 * @Description: 库迪多选
 * @Author: Kerwin
 * @Date: 2025-05-08 16:19:21
 * @LastEditTime: 2025-08-19 16:33:52
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="goodsChoose">
    <!-- 可选类 -->
    <view class="optionalBox" v-if="goodsItem.specifications">
      <view
        class="optionalItem"
        v-for="(item, index) in goodsItem.specifications"
        :key="item.id"
      >
        <view class="goodsName">{{ item.specificationName }}</view>
        <view class="goodsItem">
          <view
            class="optional"
            :class="{ activeOptional: goods.defaultItem }"
            @click="handleOptionalClick(item.specificationName, goods)"
            v-for="(goods, index) in item.ingredients"
            :key="goods.ingredientsId"
          >
            <view class="name">
              {{ goods.ingredientsName }}
            </view>
            <!-- 售罄蒙版 -->
            <view class="mode" v-if="goods.isSoldOut">
              <view class="mode-text">售罄</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 提示信息 -->
    <view class="mes">
      1．划线价格：商品展示的划横线的价格是参考价格，并非商品原价而是指不参加优惠的情况下，单品门店价格的总和（单品价总和）。当套餐内容可由您选择组合时，以套餐内可选商品的最低单价总和为为划线价，该价格仅供您参考。
      说明：
      2．非划线价格指参与优惠、使用抵扣券或代金券、在活动时间或满足活动条件、按照套餐组合购买的前提下可能支付的价格，具体的成交价格可能因参加其他活动等而发生变化，最终成交价格以订单结算页价格为准。
      3．产品及包装请以实物为准，图片仅供参考
    </view>
  </view>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  toRaw,
  toRefs,
  watch,
  nextTick
} from 'vue'
import itemImg from '@/static/xfl/item.png'
//props
const props = defineProps({
  product: {
    type: Object,
    default: () => ({})
  },
  productChoose: {
    //商品是否可选规则
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['chooseOptional'])
const chooseOptional = ref() //选中的小料数组种类
const otherStr = ref('') //选中小料code
const otherCheckStr = ref({}) //选中小料对象
const goodsItem = ref()

// 选中状态变化时触发
const handleOptionalClick = (groupName: string, item: any) => {
  if (item.isSoldOut)
    return uni.showToast({
      title: '该小料不可选',
      icon: 'none'
    })
  goodsItem.value.specifications.forEach((group: any) => {
    if (group.specificationName === groupName) {
      group.ingredients.forEach((o: any) => {
        o.defaultItem = o.ingredientsName === item.ingredientsName
      })
    }
  })

  // 触发计算并通知父组件
  const selectedIngredients = getSelectedIngredients()
  console.log(selectedIngredients, 'selectedIngredients')

  const matchedSku = findMatchingSku(selectedIngredients)

  let obj = { otherStr: matchedSku?.skuCode, otherCheckStr: '' }
  if (matchedSku && Array.isArray(matchedSku.skuSaleAttrValue)) {
    const otherCheckStr =
      '/' + matchedSku.skuSaleAttrValue.map((v: any) => v.value).join('/')
    obj.otherCheckStr = otherCheckStr
  }
  goodsItem.value.otherStr = obj.otherStr
  goodsItem.value.otherCheckStr = obj.otherCheckStr
  emit('chooseOptional', goodsItem.value)
}

// 获取所有被选中的小料名称
const getSelectedIngredients = (): string[] => {
  const selectedNames: string[] = []

  if (!goodsItem.value.specifications) return selectedNames

  goodsItem.value.specifications.forEach((group: any) => {
    group.ingredients.forEach((ingredient: any) => {
      if (ingredient.defaultItem) {
        selectedNames.push(ingredient.ingredientsName)
      }
    })
  })
  return selectedNames
}

// 根据选中小料匹配对应的 sku
const findMatchingSku = (selectedIngredients: string[]) => {
  const { skuList: skus } = goodsItem.value

  if (!Array.isArray(skus)) return null

  return skus.find((sku: any) => {
    if (!Array.isArray(sku.skuSaleAttrValue)) return false

    const specNames = sku.skuSaleAttrValue.map((v: any) => v.value)

    return (
      selectedIngredients.length === specNames.length &&
      selectedIngredients.every((name) => specNames.includes(name))
    )
  })
}

// 初始化默认选中项
const initDefaultSelection = () => {
  const selectedIngredients = getSelectedIngredients()
  const matchedSku = findMatchingSku(selectedIngredients)
  let obj = { otherStr: matchedSku?.skuCode, otherCheckStr: '' }
  if (matchedSku && Array.isArray(matchedSku.skuSaleAttrValue)) {
    const otherCheckStr =
      '/' + matchedSku.skuSaleAttrValue.map((v: any) => v.value).join('/')
    obj.otherCheckStr = otherCheckStr
  }
  goodsItem.value.otherStr = obj.otherStr
  goodsItem.value.otherCheckStr = obj.otherCheckStr
  emit('chooseOptional', goodsItem.value)
}

// 监听 product 变化，重新初始化
watch(
  () => props.product,
  (newVal) => {
    if (newVal) {
      goodsItem.value = JSON.parse(JSON.stringify(newVal))
      initDefaultSelection()
    }
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
.goodsChoose {
  // height: calc(100vh - 400rpx);
  // margin-bottom: 1300rpx;
  background-color: #fff;
}

.goodsSize1 {
  .goodsItem {
    display: flex;
    flex-wrap: wrap;

    .required {
      width: 150rpx;
      height: 160rpx;
      border-radius: 10rpx;
      text-align: center;
      margin: 30rpx;
      // margin-bottom: 50rpx;
      border: 2rpx solid #f1f1f1;

      // .img{
      //     height: 160rpx;

      // }
      .name {
        font-size: 24rpx;
      }
    }
  }

  .goodsSize1_1 {
    font-weight: 700;
    margin: 40rpx 0;
  }

  .goodsSize1_2 {
    margin-bottom: 40rpx;
  }
}

.optionalBox {
  .optionalItem {
    .goodsItem {
      display: flex;
      flex-wrap: wrap;

      .optional {
        position: relative;
        padding: 0 10rpx;
        min-width: 150rpx;
        height: 60rpx;
        line-height: 60rpx;
        border: 2rpx solid #f1f1f1;
        border-radius: 10rpx;
        text-align: center;
        margin: 30rpx;
        // margin-bottom: 80rpx;
        background-color: #f6f5f8;
        //color: #949496;

        .mode {
          position: absolute;
          top: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(25, 14, 14, 0.4);

          .mode-text {
            color: #e9e9e9;
          }
        }

        .name {
          font-size: 24rpx;
        }
      }
    }
  }
}

.goodsName {
  font-size: 28rpx;
  // color: #969696;
  color: #333;
  font-weight: 700;
  margin: 20rpx 0;
}

.mes {
  height: 500rpx;
  font-size: 20rpx;
  color: #969696;
  margin-top: 50rpx;
}

//选中了小料
.activeOptional {
  color: #ea7721 !important;
  border: 2rpx solid #ff6c18 !important;
  background-color: #fef1ec !important;
  /* 蓝色半透明蒙版 */
  //   opacity: 0.8; /* 可选：整体透明度控制 */
}
</style>
